<?php
/**
 * Created by PhpStorm.
 * User: 17274
 * Date: 2018/3/28
 * Time: 14:21
 */

namespace app\admin\controller;

use app\admin\helper\LangHelper;
use app\admin\model\LogsM;
use app\admin\model\ResourceButtonM;
use app\admin\model\ResourceM;
use app\admin\model\RoleM;
use app\admin\model\UserM;
use app\admin\service\ConsoleS;
use think\Config;
use think\Cookie;
use think\Session;

class Index extends Base
{
    protected $userM;
    protected $roleM;
    protected $resourceM;
    protected $resourceButtonM;
    protected $logsM;

    /*
     * 依赖注入Model
     * */
    public function __construct(UserM $userM,RoleM $roleM,ResourceM $resourceM,ResourceButtonM $resourceButtonM,LogsM $logsM){
        parent::__construct();
        $this->userM = $userM;
        $this->roleM = $roleM;
        $this->resourceM = $resourceM;
        $this->resourceButtonM = $resourceButtonM;
        $this->roleM = $roleM;
        $this->logsM = $logsM;
    }

    /**
     * 登录逻辑
     */
    public function login(){
        if ($this->request->isPost()){
            $username=input("post.username/s");
            $password=input("post.password/s");
            $rember=input('post.rember/s');
            $map["username"]=$username;
            $map["password"]=md5($password);
            $map["status"]=1;
            $data=$this->userM->getOneByMap($map);
            $last_sql = $this->userM->getLastSql();
            if(count($data)==1){
                //如果该用户角色为禁用状态则禁止登录
                $role = $this->roleM->getByRoleId($data['role_id']);
                if(!empty($role) && $role->status){
                    $role = $role->toArray();
                    //加载ac-resource
                    $acResource = $this->resourceM->listAll($role['role_id']);
                    Session::set("ac-resource",$acResource);
                    //加载button-resource
                    $buttonResource = $this->resourceButtonM->listAll($role['role_id']);
                    Session::set("button-resource",$buttonResource);
                    Session::set('username',$username);
                    Session::set('name',$data['name']);
                    Session::set('role_id',$role['role_id']);
                    if ($rember=='true'){
                        Cookie::set("username", $username,  3600*24*2);
                        Cookie::set("password", $password, 3600*24*2);
                        Cookie::set("rember", true,  3600*24*2);
                    }else{
                        Cookie::delete("username");
                        Cookie::delete("password");
                        Cookie::delete("rember");
                    }
                    $log = [
                        'op_uid' => Session::get('username'),
                        'op_module' => '用户登录',
                        'op_type' => 'login',
                        'op_origin' => 'user',
                        'op_data' => $username,
                        'op_ip' => getIP(),
                        'op_sql' => $last_sql,
                    ];
                    LogsM::add($log);
                    pr_log($log,'operate');
                    $this->success('登录成功');
                }
                $this->error("该账户权限被禁用",'login');

            }else {
                $this->error("账号或密码错误/账户被禁用",'login');
            }
        }
        $this->assign("username",Cookie::has("username")?Cookie::get("username"):'');
        $this->assign("password",Cookie::has("password")?Cookie::get("password"):'');
        $this->assign("rember",Cookie::has("rember")?Cookie::get("rember"):'');
        return $this->fetch('login');
    }

    public function refresh_cache(){
        $map["username"] = $username =Session::get('username');
        $map["status"] = 1;
        $data = $this->userM->getOneByMap($map);
        if(count($data) == 1){
            //如果该用户角色为禁用状态则禁止登录
            $role = $this->roleM->getByRoleId($data['role_id']);
            if(!empty($role) && $role->status){
                //加载ac-resource
                $acResource = $this->resourceM->listAll($role['role_id']);
                Session::set("ac-resource",$acResource);
                //加载button-resource
                $buttonResource = $this->resourceButtonM->listAll($role['role_id']);
                Session::set("button-resource",$buttonResource);
                Session::set('username',$username);
                Session::set('name',$data['name']);
                Session::set('role_id',$role['role_id']);
                return op_success();
            }
        }
        Session::clear();
        return op_msg(0,'角色禁用，正在剔除用户');
    }

    /**
     * 退出逻辑  clear session
     * @return array|mixed
     */
    public function logout(){
        $log = [
            'op_uid' => Session::get('username'),
            'op_module' => '用户登出',
            'op_type' => 'logout',
            'op_data' => 'clear session',
            'op_ip' => getIP(),
        ];
        LogsM::add($log);
        pr_log($log,'operate');
        Session::clear();
        if ($this->request->isPost())
            return op_success();
        else
            $this->redirect('login');
    }

    /*
     * 主页
     * */
    public function index(){
        $menu = LangHelper::convertLang(Config::get('menu'));
        $acResource = Session::get("ac-resource");
        //ac-权限验证
        foreach ($menu as $k1=>$m)
            foreach ($m['sub_link'] as $k2=>$sub)
                if (!in_array($sub['ac'],$acResource) && Session::get("username") != 'admin')
                    unset($menu[$k1]['sub_link'][$k2]);
        //校验子菜单 如果子菜单全部没权限则主菜单也unset
        foreach ($menu as $k=>$item) {
            if (empty($item['sub_link']))
                unset($menu[$k]);
        }
        $this->assign('nav',$menu);
        return $this->fetch('index');
    }

    /**
     * 控制台
     * @return mixed
     */
    public function console(){
        if ($this->request->isPost()) {
            return (new consoleS())->listData($this->logsM);
        }
        return $this->fetch('console');
    }

    /**
     * 切换语言
     */
    public function switch_lang(){
        $code = input("post.code/s");
        Cookie::set('curr_lang',$code,0);
        return op_success();
    }

}